# -*- coding: utf-8 -*-
"""
乒乓球培训管理系统 - 个人资料视图

个人资料管理相关的路由处理
包括查看、编辑、密码修改、头像上传等功能
"""

from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
from flask_login import login_required, current_user
from werkzeug.security import generate_password_hash
from sqlalchemy import and_

from app.forms.profile_forms import (
    ProfileBasicForm, CoachProfileForm, ChangePasswordForm,
    AvatarUploadForm, AccountSettingsForm, DeleteAccountForm
)
from app.models.user import User
from app.models import db
from app.utils.file_upload import save_uploaded_file, delete_uploaded_file, validate_image_file

# 创建个人资料蓝图
profile_bp = Blueprint('profile', __name__)


@profile_bp.route('/view')
@login_required
def view():
    """
    查看个人资料页

    显示用户的完整个人信息
    """
    # 获取用户统计信息
    stats = get_user_statistics(current_user)

    return render_template(
        'profile/view.html',
        user=current_user,
        stats=stats
    )


@profile_bp.route('/edit', methods=['GET', 'POST'])
@login_required
def edit():
    """
    编辑个人资料页

    用户可以编辑自己的基本信息
    教练有额外的专业信息编辑选项
    """
    # 根据用户角色选择不同的表单
    if current_user.is_coach():
        form = CoachProfileForm()
    else:
        form = ProfileBasicForm()

    if request.method == 'GET':
        # 填充表单数据
        form.real_name.data = current_user.real_name
        form.phone.data = current_user.phone
        form.email.data = current_user.email
        form.gender.data = current_user.gender
        form.age.data = current_user.age
        form.bio.data = getattr(current_user, 'bio', '')

        # 如果是教练，填充额外字段
        if current_user.is_coach():
            form.coach_level.data = getattr(current_user, 'coach_level', 'junior')
            form.hourly_rate.data = str(getattr(current_user, 'hourly_rate', ''))
            form.experience_years.data = 0  # 这个字段模型中没有，暂时设为0
            form.teaching_style.data = ''  # 这个字段模型中没有，暂时为空
            form.achievements.data = ''  # 这个字段模型中没有，暂时为空

    if request.method == 'POST':
        if form.validate_on_submit():
            try:
                # 更新基本信息
                current_user.real_name = form.real_name.data
                current_user.email = form.email.data
                current_user.gender = form.gender.data
                current_user.age = form.age.data
                current_user.bio = form.bio.data

                # 如果是教练，更新额外信息
                if current_user.is_coach():
                    current_user.coach_level = form.coach_level.data
                    if form.hourly_rate.data:
                        from decimal import Decimal
                        current_user.hourly_rate = Decimal(form.hourly_rate.data)
                    # 注意：experience_years, teaching_style, achievements 字段在当前模型中不存在
                    # 如果需要这些字段，需要先添加到User模型中

                db.session.commit()
                flash('个人资料更新成功！', 'success')
                return redirect(url_for('profile.view'))

            except Exception as e:
                db.session.rollback()
                flash(f'更新失败：{str(e)}', 'error')
        else:
            # 显示表单验证错误
            for field, errors in form.errors.items():
                for error in errors:
                    flash(f'{form[field].label.text}: {error}', 'error')

    return render_template(
        'profile/edit.html',
        form=form,
        user=current_user
    )


@profile_bp.route('/change-password', methods=['GET', 'POST'])
@login_required
def change_password():
    """
    修改密码页

    用户可以修改自己的登录密码
    """
    form = ChangePasswordForm()

    if request.method == 'POST':
        if form.validate_on_submit():
            try:
                # 更新密码
                current_user.password_hash = generate_password_hash(form.new_password.data)
                db.session.commit()

                flash('密码修改成功！', 'success')
                return redirect(url_for('profile.view'))

            except Exception as e:
                db.session.rollback()
                flash(f'密码修改失败：{str(e)}', 'error')
        else:
            # 显示表单验证错误
            for field, errors in form.errors.items():
                for error in errors:
                    flash(f'{form[field].label.text}: {error}', 'error')

    return render_template(
        'profile/change_password.html',
        form=form
    )


@profile_bp.route('/upload-avatar', methods=['GET', 'POST'])
@login_required
def upload_avatar():
    """
    上传头像页

    用户可以上传和裁剪头像
    """
    form = AvatarUploadForm()

    if request.method == 'POST':
        if form.validate_on_submit():
            try:
                avatar_file = form.avatar.data

                # 验证图片文件
                if not validate_image_file(avatar_file):
                    flash('请上传有效的图片文件', 'error')
                    return render_template('profile/upload_avatar.html', form=form)

                # 删除旧头像
                if current_user.photo_url:
                    delete_uploaded_file(current_user.photo_url)

                # 保存新头像
                avatar_url = save_uploaded_file(
                    avatar_file,
                    upload_type='avatar',
                    user_id=current_user.id,
                    crop_params={
                        'x': form.crop_x.data or 0,
                        'y': form.crop_y.data or 0,
                        'width': form.crop_width.data or 300,
                        'height': form.crop_height.data or 300
                    }
                )

                if avatar_url:
                    current_user.photo_url = avatar_url
                    db.session.commit()

                    flash('头像上传成功！', 'success')
                    return redirect(url_for('profile.view'))
                else:
                    flash('头像上传失败，请重试', 'error')

            except Exception as e:
                db.session.rollback()
                flash(f'头像上传失败：{str(e)}', 'error')
        else:
            # 显示表单验证错误
            for field, errors in form.errors.items():
                for error in errors:
                    flash(error, 'error')

    return render_template(
        'profile/upload_avatar.html',
        form=form
    )


@profile_bp.route('/settings', methods=['GET', 'POST'])
@login_required
def settings():
    """
    账户设置页

    用户可以设置通知和隐私选项
    """
    form = AccountSettingsForm()

    if request.method == 'GET':
        # 填充现有设置
        form.email_notifications.data = getattr(current_user, 'email_notifications', 'important')
        form.sms_notifications.data = getattr(current_user, 'sms_notifications', 'important')
        form.profile_visibility.data = getattr(current_user, 'profile_visibility', 'campus_only')
        form.show_phone.data = getattr(current_user, 'show_phone', 'no')
        form.show_email.data = getattr(current_user, 'show_email', 'no')

    if request.method == 'POST':
        if form.validate_on_submit():
            try:
                # 更新设置
                current_user.email_notifications = form.email_notifications.data
                current_user.sms_notifications = form.sms_notifications.data
                current_user.profile_visibility = form.profile_visibility.data
                current_user.show_phone = form.show_phone.data
                current_user.show_email = form.show_email.data

                db.session.commit()
                flash('账户设置更新成功！', 'success')
                return redirect(url_for('profile.settings'))

            except Exception as e:
                db.session.rollback()
                flash(f'设置更新失败：{str(e)}', 'error')
        else:
            # 显示表单验证错误
            for field, errors in form.errors.items():
                for error in errors:
                    flash(error, 'error')

    return render_template(
        'profile/settings.html',
        form=form
    )


@profile_bp.route('/delete-account', methods=['GET', 'POST'])
@login_required
def delete_account():
    """
    注销账户页

    用户可以申请注销自己的账户
    """
    form = DeleteAccountForm()

    if request.method == 'POST':
        if form.validate_on_submit():
            try:
                # 检查是否有未完成的预约或其他关联
                associations = check_user_associations(current_user)

                if associations['has_active_reservations']:
                    flash('您还有未完成的预约，无法注销账户', 'error')
                    return render_template('profile/delete_account.html', form=form, associations=associations)

                # 标记账户为注销状态（软删除）
                current_user.status = 'inactive'

                db.session.commit()

                # 登出用户
                from flask_login import logout_user
                logout_user()

                flash('账户注销申请已提交，感谢您的使用！', 'info')
                return redirect(url_for('auth.login'))

            except Exception as e:
                db.session.rollback()
                flash(f'注销失败：{str(e)}', 'error')
        else:
            # 显示表单验证错误
            for field, errors in form.errors.items():
                for error in errors:
                    flash(error, 'error')

    # 获取关联数据
    associations = check_user_associations(current_user)

    return render_template(
        'profile/delete_account.html',
        form=form,
        associations=associations
    )


@profile_bp.route('/api/avatar-upload', methods=['POST'])
@login_required
def api_avatar_upload():
    """
    头像上传API

    用于AJAX上传头像
    """
    try:
        if 'avatar' not in request.files:
            return jsonify({'success': False, 'error': '请选择头像文件'}), 400

        avatar_file = request.files['avatar']
        if avatar_file.filename == '':
            return jsonify({'success': False, 'error': '请选择头像文件'}), 400

        # 验证图片文件
        if not validate_image_file(avatar_file):
            return jsonify({'success': False, 'error': '请上传有效的图片文件'}), 400

        # 获取裁剪参数
        crop_params = {
            'x': int(request.form.get('crop_x', 0)),
            'y': int(request.form.get('crop_y', 0)),
            'width': int(request.form.get('crop_width', 300)),
            'height': int(request.form.get('crop_height', 300))
        }

        # 删除旧头像
        if current_user.photo_url:
            delete_uploaded_file(current_user.photo_url)

        # 保存新头像
        avatar_url = save_uploaded_file(
            avatar_file,
            upload_type='avatar',
            user_id=current_user.id,
            crop_params=crop_params
        )

        if avatar_url:
            current_user.photo_url = avatar_url
            db.session.commit()

            return jsonify({
                'success': True,
                'avatar_url': avatar_url,
                'message': '头像上传成功'
            })
        else:
            return jsonify({'success': False, 'error': '头像上传失败'}), 500

    except Exception as e:
        db.session.rollback()
        return jsonify({'success': False, 'error': str(e)}), 500


def get_user_statistics(user):
    """
    获取用户统计信息

    Args:
        user: 用户对象

    Returns:
        dict: 统计信息
    """
    stats = {
        'total_logins': 0,
        'account_age_days': 0,
        'last_activity': None
    }

    try:
        # 计算账户年龄
        if user.created_at:
            from datetime import datetime
            account_age = datetime.now() - user.created_at
            stats['account_age_days'] = account_age.days

        # 最后活动时间
        stats['last_activity'] = None

        # 根据角色获取特定统计
        if user.is_student():
            # 学员统计（暂时使用模拟数据，等预约模型完成后更新）
            stats.update({
                'total_reservations': 0,
                'total_coaches': 0,
                'total_spending': 0
            })
        elif user.is_coach():
            # 教练统计（暂时使用模拟数据，等预约模型完成后更新）
            stats.update({
                'total_students': 0,
                'total_classes': 0,
                'total_earnings': 0
            })
        elif user.is_campus_admin():
            # 校区管理员统计
            if user.campus:
                stats.update({
                    'campus_students': user.campus.users.filter_by(role='student', status='active').count(),
                    'campus_coaches': user.campus.users.filter_by(role='coach', status='active').count(),
                    'campus_tables': 0  # 等球台模型关系完成后更新
                })

    except Exception as e:
        print(f"获取用户统计失败: {e}")

    return stats


def check_user_associations(user):
    """
    检查用户的关联数据

    Args:
        user: 用户对象

    Returns:
        dict: 关联数据信息
    """
    associations = {
        'has_active_reservations': False,
        'active_reservations_count': 0,
        'total_reservations': 0,
        'has_pending_applications': False,
        'can_delete': True
    }

    try:
        # 检查预约记录（暂时简化，等预约模型完成后更新）
        if user.is_student():
            # 暂时设为无活跃预约
            associations['active_reservations_count'] = 0
            associations['has_active_reservations'] = False
            associations['total_reservations'] = 0

        elif user.is_coach():
            # 暂时设为无活跃课程
            associations['active_reservations_count'] = 0
            associations['has_active_reservations'] = False
            associations['total_reservations'] = 0

        # 如果有活跃预约，不能删除
        if associations['has_active_reservations']:
            associations['can_delete'] = False

    except Exception as e:
        print(f"检查用户关联数据失败: {e}")
        associations['can_delete'] = False

    return associations